import 'dart:async';
import 'dart:convert';
import 'package:find_friend/common/event_bus.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/im/custompage/msg_receive_commentpage.dart';
import 'package:find_friend/pages/im/pages/conversation_page.dart';
import 'package:find_friend/pages/im/util/event_bus.dart';
import 'package:find_friend/pages/im/util/time.dart';
import 'package:find_friend/pages/login&register/model/shared_user_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:soundpool/soundpool.dart';


class MsgHomePage extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return _MsgHomePageState();
  }
}

class _MsgHomePageState extends State<MsgHomePage> {

  List<int> displayConversationType = [
    RCConversationType.Private,
  ];
  List headList = ["", ""];
  List conList = [];
  List<String> needToAddFriendList = []; // 需要加好友的列表
  Timer _timer;
  int upvotes = 0;
  int replys = 0;
  int allcount = 0;
  String mineTargetId = "";
  List<String> specialSound = [];

   @override
  void dispose() {
    EventBus.instance.removeListener(EventKeys.ConversationPageDispose);
    EventMineBus.instance.removeListener(EventMineKeys.RefreshMessageList);
    _timer?.cancel();
    _timer = null;
    super.dispose();
  }
  @override
  void initState() {
    super.initState();
    addIMhandler();
    updateConversationList();
    _beginTimer();// 定时查询未读数
    _requestUnreadCount(); // 查询未读数

    SharedPreferences.getInstance().then((value) {
      specialSound = value.getStringList(KEY_special_sound);
    });
    SharedUserInfo.instance().then((value) => mineTargetId = value.mobile);
  }

  /// 播放音频
  void _playAudio() async {
    
    Soundpool pool = Soundpool(streamType: StreamType.notification);
    int soundId = await rootBundle.load("assets/audio/notice.mp3").then((value){
      return pool.load(value);
    });
    await pool.play(soundId);
  }

  addIMhandler() {
    EventBus.instance.addListener(EventKeys.ReceiveMessage, (map) {
      Message msg = map["message"];
      int left = map["left"];
      bool hasPackage = map["hasPackage"];
      bool isDisplayConversation = msg.conversationType != null &&
          displayConversationType.contains(msg.conversationType);
      //如果离线消息过多，那么可以等到 hasPackage 为 false 并且 left == 0 时更新会话列表
      if (!hasPackage && left == 0 && isDisplayConversation) {
        updateConversationList();
      }
    });

    RongcloudImPlugin.onConnectionStatusChange = (int connectionStatus) {
      if (RCConnectionStatus.Connected == connectionStatus) {
        updateConversationList();
      }
    };

    RongcloudImPlugin.onRecallMessageReceived = (Message message) {
      updateConversationList();
    };

    RongcloudImPlugin.onMessageReceived = (Message msg,int left) {
      updateConversationList();
      _updateUnreadCount();
      /// 如果接收到陌生人的消息自动加好友
      String targetId = msg.content.sendUserInfo.userId;
      if(needToAddFriendList.contains(targetId)) { 
        _requestAddFriend(targetId);
      }

      // 播放特别关心的提示音量
      if(specialSound.contains(targetId)) {
        _playAudio();
      }
      print("receive message messsageId:"+msg.messageId.toString()+" left:"+left.toString());
    };

    // 发送消息给别人刷新列表
    EventMineBus.instance.addListener(EventMineKeys.RefreshMessageList, (arg) => updateConversationList());
  }

  _updateUnreadCount() {
    RongcloudImPlugin.getTotalUnreadCount((count, code){
      allcount += count;
      EventMineBus.instance.commit(EventMineKeys.IMMessageCount, allcount);
    });
  }

  _beginTimer() {
    _timer = Timer.periodic(const Duration(seconds: 60), (timer) { 
      _requestUnreadCount();
    });
  }

  _requestUnreadCount() {
    Networktool.request(API.friendUnread, method: NETWORKHTTPMethod.GET, success: (data){
      if(data != null) {
        upvotes = data["data"]['upvotes'];
        replys = data['data']['replys'];
        if(mounted) {
          setState(() {
          
          });
        }
        allcount = upvotes + replys;
        _updateUnreadCount();
      }
    });
  }

  /// 自动加好友
  void _requestAddFriend(String targetId) {
    Networktool.request(API.friendauto, params: {"mobile": targetId}, method: NETWORKHTTPMethod.POST, success: (data){
      if(data != null) {
        needToAddFriendList.remove(targetId);
        SharedPreferences.getInstance().then((value) => value.remove(targetId));
      }
    });
  }

  updateConversationList() async {
    List<dynamic> list = await RongcloudImPlugin.getConversationList(displayConversationType);
    if (list != null) {
      // list.sort((a,b) => b.sentTime.compareTo(a.sentTime));
      conList.clear();
      for(var i = 0; i < list.length; i++) {
        Conversation element = list[i];
        if(element.latestMessageContent != null) {
          // 扩展字段保存了发送方的mobile
          if(mineTargetId == element.senderUserId) {
            Map temp = json.decode(element.latestMessageContent.sendUserInfo.extra);
            element.latestMessageContent.decodeUserInfo(temp);
          }
          conList.add(element);
        }
      }
    }
    _updateUnreadCount();
    _renfreshUI();
  }

  void _renfreshUI() {
    if(mounted) setState(() {});
  }

  void _deleConversation(Conversation con) {
    RongcloudImPlugin.deleteMessages(con.conversationType, con.targetId, (code) => null);
    setState(() {
      conList.remove(con);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: ListView.builder(
        itemCount: headList.length + conList.length,
        itemBuilder: (context, index){
          if(index ==0) {
            return MsgHeaderCell(
              icon: "assets/tx135.png",
              title: "赞",
              count: upvotes,
              onTap: (){
                setState((){
                  allcount -= upvotes;
                  upvotes = 0;
                });
                _updateUnreadCount();
                Navigator.of(context).pushNamed("/msgraise");
              },
            );
          } else if(index == 1) {
            return MsgHeaderCell(
              icon: "assets/354643.png",
              title: "评论",
              count: replys,
              onTap: () async {
                int unreadcount = await push(context, MsgReceiveComment());
                if(unreadcount == null) return;
                setState(() {
                  if(unreadcount == -1) {
                    allcount -= replys;
                    replys = 0;
                  } else {
                    allcount -= unreadcount;
                    replys -= unreadcount;
                  }
                });
                _updateUnreadCount();
              },
            );
          } else {
            return Slidable(
              actionPane: SlidableDrawerActionPane(),
              actionExtentRatio: 0.18,// 按钮所占的宽度
              secondaryActions: [
                SlideAction(
                  color: APP_verify_error_color,
                  onTap: (){
                    _deleConversation(conList[index - 2]);
                  },
                  child: Text("删除",style: instanceTextStyle(11, Colors.white),),
                ),
              ],
              child: MsgCell(
                conList[index - 2], 
                mineTargetId: mineTargetId,
                onResetUnRead: (conversation){
                  setState(() {    
                    conversation.unreadMessageCount = 0;
                  });
                },
                onReceviveAddFriend: (targetid, isadd){
                  if(isadd) {
                    needToAddFriendList.add(targetid);
                  } else {
                    needToAddFriendList.remove(targetid);
                  }
                },
              ),
            );
          }
        }
      ),
    );
  }
}

class MsgHeaderCell extends StatelessWidget {

  final String title;
  final String icon;
  final int count;
  final Function onTap;
  

  const MsgHeaderCell({Key key, this.title, this.icon, this.count, this.onTap}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.only(top: 10, left: 15, right: 10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Image.asset(icon, width: 46, height: 46, fit: BoxFit.cover,),
                SizedBox(width: 5,),
                Expanded(child: Text(title, style: instanceTextStyle(14, APP_font_black),)),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 3.5),
                  decoration: BoxDecoration(
                    color: count == 0 ? Colors.transparent : APP_verify_error_color,
                    borderRadius: BorderRadius.circular(10)
                  ),
                  child: Text(count > 99 ? "99+" : count.toString(), style: instanceTextStyle(11, Colors.white),),
                ),
                SizedBox(width: 10,),
                Image.asset("assets/my-next.png")
              ],
            ),
            SizedBox(height: 5),
            Divider(height: 0.5, color: APP_divider_color, indent: 51, endIndent: 0,)
          ],
        ),
      ),
    );
  }
}

class MsgCell extends StatelessWidget {

  Conversation conversation;
  UserInfo info;
  final String mineTargetId;
  final Function(Conversation con) onResetUnRead;
  final Function(String targetId, bool isadd) onReceviveAddFriend;
  
  MsgCell(Conversation con,{this.onResetUnRead, this.mineTargetId, this.onReceviveAddFriend}) {
    this.conversation = con;
    if (con.conversationType == RCConversationType.Private) {
      this.info = conversation.latestMessageContent.sendUserInfo;
    }
  }

  String _getPlaceHolder() {
    if(conversation.latestMessageContent is GifMessage) {
      return "[表情]";
    }else if(conversation.latestMessageContent is VoiceMessage) {
      return "[语音]";
    } else if(conversation.latestMessageContent is ImageMessage) {
      return "[图片]";
    }
    return conversation.latestMessageContent.conversationDigest();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        if(onResetUnRead != null) onResetUnRead(conversation);
        Map arg = {"coversationType":RCConversationType.Private,"targetId":conversation.targetId, "nickname":info.name,};
        push(context, ConversationPage(arguments: arg, onReceviveAddFriend: onReceviveAddFriend,));
      },
      child: Container(
        color: Colors.white,
        height: 60.h,
        padding: const EdgeInsets.only(top: 10, left: 15, right: 15),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            PhysicalModel(
              color: Colors.white,
              clipBehavior: Clip.antiAlias,
              shape: BoxShape.circle,
              child: Image.network(
                info?.portraitUri,
                fit: BoxFit.cover,
                width: 46.w,
                height: 46.w,
              ),
            ),
            SizedBox(width: 8,),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(info?.name ?? conversation.targetId, style: instanceTextStyle(14, APP_font_black),),
                  SizedBox(height: 5,),
                  Row(
                    children: [
                      Offstage(
                      offstage: conversation.sentStatus != RCSentStatus.Failed,
                      child: Padding(
                        padding: const EdgeInsets.only(right: 1.0),
                        child: Icon(Icons.error, size: 15, color: APP_verify_error_color),
                      )
                    ),
                      Text(_getPlaceHolder(), maxLines: 1, overflow: TextOverflow.ellipsis, style: instanceTextStyle(12, APP_font_grey),),
                    ],
                  ),
                ],
              ),
            ),
            SizedBox(width: 15,),
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Text(TimeUtil.convertTime(conversation.sentTime), style: instanceTextStyle(11, const Color(0xff999999)),),
                SizedBox(height: 5,),
                Opacity(
                  opacity: conversation.unreadMessageCount != 0 ? 1 : 0,
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 3.5),
                    decoration: BoxDecoration(
                      color: APP_verify_error_color,
                      borderRadius: BorderRadius.circular(10)
                    ),
                    child: Text(conversation.unreadMessageCount > 99 ? "99+" : conversation.unreadMessageCount.toString(), style: instanceTextStyle(11, Colors.white),),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}